package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Todo;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class TodoDao {

	DBHelp<Todo> db = new DBHelp<Todo>();
	
	public void save(Todo todo) {
		String sql = "insert into t_todo(todo,done) values(?,?)";
		db.executeSQL(sql, todo.getTodo(),todo.isDone());
	}
	
	public void update(Todo todo) {
		String sql = "update t_todo set todo = ?,done = ? where id = ?";
		db.executeSQL(sql, todo.getTodo(),todo.isDone(),todo.getId());
	}
	
	public void del(int id) {
		String sql = "delete from t_todo where id = ?";
		db.executeSQL(sql, id);
	}
	
	public List<Todo> findAll() {
		String sql = "select id,todo,done,createtime from t_todo order by createtime desc";
		return db.executeQueryToList(sql, new TodoRowMapper());
	}
	
	public Todo findById(int id) {
		String sql = "select id,todo,createtime,done from t_todo where id = ?";
		return db.executeQueryToObject(sql, new TodoRowMapper(), id);
	}
	
	private class TodoRowMapper implements RowMapper<Todo>{
		public Todo mapRow(ResultSet rs) throws SQLException {
			Todo todo = new Todo();
			todo.setId(rs.getInt("id"));
			todo.setCreatetime(rs.getString("createtime"));
			todo.setDone(rs.getBoolean("done"));
			todo.setTodo(rs.getString("todo"));
			return todo;
		}
		
		
	}
}
